  /**************************************************************************/
  /*                                                                        */
  /*  System  Name :  ICIM                                                  */
  /*                                                                        */
  /*  Description  :  Bis_CUS_LOC Management                                */
  /*                                                                        */
  /*  MODIFICATION HISTORY                                                  */
  /*    Date     Ver     Name          Description                          */
  /* ---------- ----- ----------- ----------------------------------------- */
  /* 2013/09/06 N0.00   meijiao.C      Initial release                      */
  /*                                                                        */
  /**************************************************************************/
$(document).ready(function() {
	$("#tabDiv").tab('show');
	var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPBISCUS : "XPBISCUS",
        T_XPLSTDAT : "XPLSTDAT"
	}
	//var locType = ['R','S'];
	var locType = ['R'];
	var controlsQuery = {
        W                  : $(window)             ,
        customer_id        : $("#customerIDTxt"),
        customer_name      : $("#customerNameTxt"),
        customer_dsc       : $("#customerDscTxt"),
        customerTypSel     : $("#customerTypSel"),
        dataSeqIdTxt       : $("#dataSeqIdTxt"),
        loc_info           : $("#updateLocDialog_locIDTxt"),
        recieve_loc        : $("#updateLocDialog_SlocIDTxt"),
        inputCom           : $("input"),
        selectCom          : $("select"),
        loc_type           : $("#updateLocDialog_locTypSel"),
        updatelocDialog    : $("#updateLocDialog"),
        locType_dsc        : $("#locTypSelDesSpn"),
        mainGrd   :{
            grdId     : $("#customerListGrd")   ,
            grdPgText : "#customerListPg"       ,
            fatherDiv : $("#customerListDiv")
        },
        locGrd   : {
        	grdId     : $("#locListGrd")   ,
            grdPgText : "#locListPg"       ,
            fatherDiv : $("#locListDiv")
        }
	}
	window.delete_func = function(id){
		strval=id.substr(12,1) - 1;	
        buttonCounts1[strval]=false;
		$("#"+id).remove();
	};
	var btnQuery = {
        f1 : $("#f1_query_btn"),
        f4 : $("#f4_del_btn"),
        f5 : $("#f5_upd_btn"),
        f6 : $("#f6_add_btn"),
        f8 : $("#f8_register_btn"),
        addBtn : $("#addbtn"),
        addloc : $("#addloc"),
        execute: $("#updateLocDialog_queryBtn")
	}
	
	var toolFunc = {
    	initFnc : function(){
    		toolFunc.diabledInput();
    		controlsQuery.inputCom.val("");
    		  $("form").submit(function(){
			      return false;
			  });
			  controlsQuery.locGrd.grdId.on("click",".modifyCss",toolFunc.modifyFnc);
   	    controlsQuery.locGrd.grdId.on("click",".deleteCss",toolFunc.deleteFnc);
    	},
    	initCustomerTypSel:function(){
    		controlsQuery.customerTypSel.empty();
    		SelectDom.addSelect(controlsQuery.customerTypSel, "0", "客户");
    		SelectDom.addSelect(controlsQuery.customerTypSel, "1", "客户&厂商");
    		SelectDom.addSelect(controlsQuery.customerTypSel, "2", "厂商");
    	},
    	diabledInput:function(){
    		controlsQuery.customer_dsc.attr({'disabled':true});
    		controlsQuery.customer_id.attr({'disabled':true});
    		controlsQuery.customer_name.attr({'disabled':true});
    		controlsQuery.customerTypSel.attr({'disabled':true});
    	},
    	QueryCustInfoProc:function(){
    		var crGrid,
    			data,
    			inObj,
    			outObj;
			controlsQuery.dataSeqIdTxt.val("");
    		crGrid = controlsQuery.mainGrd.grdId;
			var rowid  = crGrid.jqGrid('getGridParam','selrow');
			data = crGrid.jqGrid('getRowData',rowid);
			controlsQuery.customer_id.val( data['data_item'] );
			controlsQuery.customer_dsc.val( data['ext_1'] );
			controlsQuery.customer_name.val( data['data_ext'] );
			controlsQuery.customerTypSel.val( data['ext_5']);
			controlsQuery.dataSeqIdTxt.val(data['data_seq_id']);
			controlsQuery.locGrd.grdId.jqGrid("clearGridData");
			var iary = {
				cus_id_fk : data['data_item']
			}
			inObj = {
				trx_id : VAL.T_XPBISCUS,
				action_flg:'Q',
				iary: iary
			}
			outObj = comTrxSubSendPostJson( inObj );
			if( outObj.rtn_code == VAL.NORMAL){
				if( outObj.tbl_cnt >0){
					setGridInfo(outObj.oary,"#locListGrd");
					toolFunc.addGridButton();
				}
			}
    	},
    	addDivfunc:function(){
    		var itemOriginal =document.getElementsByName("address");
    		for(var i=0;i < buttonCounts1.length;i++){
              if(buttonCounts1[i] == false){
                    cti=i+1;
                    buttonCounts1[i]=true;
                     break;
              }
            }
    		var str ="<div id="+"addresslist_"+cti+">"
    		    str += "<div class='control-group span3' name='address'>";
    			str += "<label class='control-label span1' for="+"Raddress_"+cti+">收货地址"+cti;
    			str += "</label>";
    			str += "<div class='controls'>";
    			str += "<input type='text' class='span2' id="+"Raddress_"+cti+">";
    			str += "</div>";
    			str += "</div>";
    			str += "<div class='control-group span3'>";
    			str += "<label class='control-label span1' for="+"Saddress_"+cti+">送货地址"+cti;
    			str += "</label>";
    			str += "<div class='controls'>";
    			str += "<input type='text' class='span2' id="+"Saddress_"+cti+">";
    			str += "</div>";
    			str += "</div>";
    			str += "<div class='control-group span1'>";
    			str += "<button class='btn btn-danger' onclick=delete_func('addresslist_"+cti+"') id="+"delete_"+cti+">删除";
    			str += "</button>";
    			str += "</div>";
    			str += "</div>";
    		$("#adressDiv").append(str);
    	},
    	addGridButton:function(){
		    var ids=controlsQuery.locGrd.grdId.jqGrid('getDataIDs');
		    for(var i=0; i<ids.length; i++){
		        var id=ids[i];   
		        var modify = "<button id=" + "'mod" + ids[i] + "' class='modifyCss' " + " style='color:#f60'>修改</button>";  
		        var deleteItem = "<button id=" + "'del" + ids[i] + "' class='deleteCss' " + " style='color:#f60'>删除</button>";  
		        controlsQuery.locGrd.grdId.jqGrid('setRowData', ids[i], { modifyItem: modify,deleteItem:deleteItem});
		      //  $("#mod" + ids[i]).click( toolFunc.modifyFnc );
		      //  $("#del" + ids[i]).click( toolFunc.deleteFnc );
			}
   	 	},
   	 	
   	 	locDialogShowUfunc: function(){
   	 		
   	 		controlsQuery.loc_type.empty();
   	 		for( i =0;i<locType.length;i++){
			       controlsQuery.loc_type.append('<option role="option" value="'
	                 + locType[i] + '">' + locType[i]
	                 + "</option>");
   	 		}
   	 		controlsQuery.loc_type.attr("disabled",false);
   	 		if( controlsQuery.loc_type.find("option:selected").text() == "R" ){
	    		controlsQuery.locType_dsc.text("收货地址");
	    	}else if( controlsQuery.loc_type.find("option:selected").text() == "S" ){
	    		controlsQuery.locType_dsc.text("送货地址");
	    	}
   	 		controlsQuery.loc_info.val("");
	   	 	controlsQuery.loc_type.select2({
	   	    	theme : "bootstrap"
	   	    });
   	 	},
   	 	locDialofShowFunc:function(rowid){
   	 		
   	 		var crGrid,
   	 			i;
   	 			crGrid = controlsQuery.locGrd.grdId;
//				var rowid  = crGrid.jqGrid('getGridParam','selrow');
				var data = crGrid.jqGrid('getRowData',rowid);
				controlsQuery.loc_info.val("");
				controlsQuery.loc_type.empty();
				controlsQuery.loc_type.append('<option role="option" value="'
	                 + data['loc_type'] + '">' + data['loc_type']
	                 + "</option>");
	            if( $.trim(data['loc_type']) == "R" ){
	            	controlsQuery.locType_dsc.text("收货地址");
	            }else if( $.trim(data['loc_type']) == "S" ){
	            	controlsQuery.locType_dsc.text("送货地址");
	            }
	            controlsQuery.loc_type.attr("disabled",true);
				controlsQuery.loc_info.val( data['loc_info']);
				controlsQuery.loc_type.select2();
   	 	},
   	 	updateLocInfo:function(){
   	 		var inObj,
   	 			outObj,
   	 			crGrid,
   	 			iary = [];
   	 		crGrid = controlsQuery.locGrd.grdId;
			var rowid  = crGrid.jqGrid('getGridParam','selrow');
			var data = crGrid.jqGrid('getRowData',rowid);
			if( $.trim( controlsQuery.loc_info.val() ) == ""){
				showErrorDialog("","请填写地址信息!");
				return false;
			}
			iary = {
				cus_id_fk  : data['cus_id_fk'],
				cus_seq_id : data['cus_seq_id'],
				loc_type   : data['loc_type'],
				loc_info   : controlsQuery.loc_info.val()
			
			}
   	 		inObj = {
   	 			trx_id : VAL.T_XPBISCUS,
   	 			action_flg : "U",
   	 			tbl_cnt : 1,
   	 			evt_user : VAL.EVT_USER,
   	 			iary :iary
   	 		}
   	 		outObj = comTrxSubSendPostJson( inObj );
			if( outObj.rtn_code == VAL.NORMAL){
				showSuccessDialog("更新成功");
				controlsQuery.updatelocDialog.modal("hide");
				toolFunc.QueryCustInfoProc();
			}
   	 	},
   	 	addLocInfo:function(){
   	 		var inObj,
   	 			outObj,
   	 			crGrid,
   	 			iary = [],
   	 			ids,
   	 			i,
   	 			data,
   	 			no;
   	 		crGrid = controlsQuery.locGrd.grdId;
			var rowid  = crGrid.jqGrid('getGridParam','selrow');
			data = crGrid.jqGrid('getRowData',rowid);
			ids = crGrid.jqGrid('getDataIDs');
			if( $.trim( controlsQuery.loc_info.val() ) == ""){
				showErrorDialog("","请填写地址信息!");
				return false;
			}
			if( $.trim( controlsQuery.loc_type.find("option:selected").text() ) == ""){
				showErrorDialog("","请选择地址类型!");
				return false;
			}
			if( ids.length == 0){
				no =0;
			
			}
			for(i =0;i<ids.length;i++){
				rowdata = crGrid.jqGrid('getRowData',ids[i]);
				if( i == 0){
					no = parseInt(rowdata['cus_seq_id'],10);
				}else{
					if( parseInt(rowdata['cus_seq_id'],10) >no){
						no = parseInt(rowdata['cus_seq_id'],10);
					}
				}
			
			}
			iary = {
				cus_id_fk  : controlsQuery.customer_id.val(),
				cus_seq_id : parseInt(no+1,10),
				loc_type   : controlsQuery.loc_type.find("option:selected").text(),
				loc_info   : $.trim( controlsQuery.loc_info.val() )
			}
   	 		inObj = {
   	 			trx_id : VAL.T_XPBISCUS,
   	 			action_flg : "A",
   	 			tbl_cnt : 1,
   	 			evt_user : VAL.EVT_USER,
   	 			iary :iary
   	 		}
   	 		outObj = comTrxSubSendPostJson( inObj );
			if( outObj.rtn_code == VAL.NORMAL){
				showSuccessDialog("更新成功");
				controlsQuery.updatelocDialog.modal("hide");
				toolFunc.QueryCustInfoProc();
			}
   	 	},
   	 	
		  /*****
    说明:(1) addGridButton :在Grid中添加了两个Button: "修改" , "删除"
         (2) modifyFnc     :点击修改时,调用此函数.
         (3) deleteFnc     :点击删除时,调用此函数.
  *********/
  		modifyFnc:function(){
  			//toolFunc.updateLocInfo().data("update_flag","U");
  			controlsQuery.updatelocDialog.modal({
		        backdrop:true,
		        keyboard:false,
		        show:false
	    	});
	    	controlsQuery.updatelocDialog.unbind('shown.bs.modal');
		    btnQuery.execute.unbind('click');
//		    controlsQuery.updatelocDialog.bind('shown.bs.modal',toolFunc.locDialofShowFunc);
		    controlsQuery.updatelocDialog.modal("show");
		    toolFunc.locDialofShowFunc(this.id.replace("mod",""));
		    btnQuery.execute.bind('click',toolFunc.updateLocInfo);
  		},
  		deleteFnc:function(){
  			var inObj,
   	 			outObj,
   	 			crGrid,
   	 			iary = [],
   	 			ids,
   	 			i,
   	 			data,
   	 			no;
   	 		crGrid = controlsQuery.locGrd.grdId;
   	 		//var rowid  = crGrid.jqGrid('getGridParam','selrow');
   	 		
   	 	  var rowid = this.id.replace("del","")
   	 		if( rowid == null){
   	 			showErrorDialog("","请先选择选中删除的那一行.");
   	 			return false;
   	 		}
			data = crGrid.jqGrid('getRowData',rowid);
			iary = {
				cus_id_fk : data['cus_id_fk'],
				cus_seq_id: data['cus_seq_id']
			}
			inObj = {
   	 			trx_id : VAL.T_XPBISCUS,
   	 			action_flg : "D",
   	 			tbl_cnt : 1,
   	 			evt_user : VAL.EVT_USER,
   	 			iary :iary
   	 		}
   	 		outObj = comTrxSubSendPostJson( inObj );
			if( outObj.rtn_code == VAL.NORMAL){
				showSuccessDialog("删除成功");
				toolFunc.QueryCustInfoProc();
			}
  		}
  	}
	var btnFunc = {
    	query_func : function(){
    		var inObj,
    			outObj,
    			iary = [];
    		var iary = {
		      data_cate : "CUSD",
		      list_all_cus_flg  : "Y"
		    };
		    var inTrxObj = {
		        trx_id     : 'XPLSTDAT' ,
		        action_flg : 'Q'        ,
		        iary       : iary 
		    };
		    var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
		      if(  outTrxObj.rtn_code == VAL.NORMAL ) {
		        setGridInfo(outTrxObj.oary,"#customerListGrd");
		    }
    	},
    	del_func : function(){
    		var crGrid,
    		    inObj,
    			outObj,
    			iary = [],
    			rowIDs,
    			i,
    			iary=[];
    		crGrid = controlsQuery.mainGrd.grdId;
    		rowIDs = crGrid.jqGrid('getGridParam','selrow');
    		if( rowIDs == null){
    			showErrorDialog("","请选择需要删除的客户信息!");
    			return false;
    		}
			var rowData = crGrid.jqGrid('getRowData',rowIDs);
			iary= {
				data_cate : "CUSD",
				data_seq_id : rowData["data_seq_id"],
				data_item : rowData['data_item'],
    			data_ext: rowData['data_ext'],
    			ext_1 : rowData['ext_1'],
    			data_id : "1000"
			};
    		inObj = {
    			trx_id : VAL.T_XPLSTDAT,
    			action_flg: 'D',
    			tbl_cnt : rowIDs.length,
    			iary : iary
    		}
    		outObj = comTrxSubSendPostJson( inObj );
    		if( outObj.rtn_code == VAL.NORMAL ){
    			showSuccessDialog("删除成功");  
    			btnFunc.query_func();
    		}
    	},
    	update_func : function(){
    		btnQuery.f8.data("register_flg",'U');
    		controlsQuery.customer_dsc.attr("disabled",false);
    		controlsQuery.customer_name.attr("disabled",false);
    		controlsQuery.customerTypSel.attr("disabled",false);
    		$("#tab2").removeAttr("href");
    		$("#tab4").removeAttr("href");
    	},
    	add_func : function(){
    		controlsQuery.inputCom.val("");
    		btnQuery.f8.data("register_flg",'A');
    		controlsQuery.customer_id.attr("disabled",false);
    		controlsQuery.customer_id.focus();
    		controlsQuery.customer_dsc.attr("disabled",false);
    		controlsQuery.customer_name.attr("disabled",false);
    		controlsQuery.customerTypSel.attr("disabled",false);
    		$("#tab2").removeAttr("href");
    		$("#tab4").removeAttr("href");
    	},
    	register_func:function(){
    		
	        var customer_id,
    			customer_dsc,
    			customer_name,
    			customer_typ,
    			data_seq_id,
    			inObj,
    			outObj,
    			iary = [],
    			action_flg;
    		action_flg = btnQuery.f8.data("register_flg");
    		if(action_flg==undefined){
	            return false;
	        }
    		customer_id = controlsQuery.customer_id.val();
    		customer_dsc = controlsQuery.customer_dsc.val();
    		customer_name = controlsQuery.customer_name.val();
    		customer_typ = controlsQuery.customerTypSel.val();
    		data_seq_id = controlsQuery.dataSeqIdTxt.val();
    		iary = {
    			data_cate : "CUSD",
    			data_id   : "1000",
    			data_item : customer_id,
    			data_ext: customer_name,
    			ext_1 : customer_dsc,
    			ext_5 : customer_typ
    		};
    		if(action_flg === "U"){
    			iary.data_seq_id = controlsQuery.dataSeqIdTxt.val();
    		}
    		inObj = {
    			trx_id :VAL.T_XPLSTDAT,
    			action_flg :action_flg,
    			tbl_cnt :1,
    			iary : iary
    		}
    		outObj = comTrxSubSendPostJson( inObj );
    		if( outObj.rtn_code == VAL.NORMAL){
    			if( action_flg == 'A'){
    				showSuccessDialog("添加客户信息成功");  
    			}else{
    				showSuccessDialog("更新客户信息成功");  
    			}

    			$("#tab2").attr("href","#tabPane_dept" );
    			$("#tab4").attr("href","#settings" );
        		controlsQuery.customer_dsc.attr("disabled",true);
        		controlsQuery.customer_name.attr("disabled",true);
        		controlsQuery.customerTypSel.attr("disabled",true);
    			btnFunc.query_func();
    		}
    	},
    	addlocfunc:function(){
//    		toolFunc.updateLocInfo().data("update_flag","A");
  			controlsQuery.updatelocDialog.modal({
		        backdrop:true,
		        keyboard:false,
		        show:false
	    	});
	    	controlsQuery.updatelocDialog.unbind('shown.bs.modal');
		    btnQuery.execute.unbind('click');
			$('[rel=tooltip]').tooltip({
	          placement:"bottom",
	          trigger:"focus",
	          animation:true
        	})
		    //controlsQuery.updatelocDialog.bind('shown.bs.modal',toolFunc.locDialogShowUfunc);
		    controlsQuery.updatelocDialog.modal("show");
		    btnQuery.execute.bind('click',toolFunc.addLocInfo);
		    toolFunc.locDialogShowUfunc();
    	}
	}
	var iniGridInfo = function(){ 
   			var grdInfoCM = [
	            {name: 'data_item'     , index: 'data_item'  , label: CUS_ID_TAG        , width: 180 },
    			{name: 'data_ext'      , index: 'data_ext'   , label: CUS_NAME_TAG      , width: 180 },
    			{name: 'ext_1'         , index: 'ext_1'      , label: CUS_DSC_TAG       , width: 180 },
    			{name: 'ext_5'         , index: 'ext_5'      , label: "客户或厂商"       , width: 180 ,hidden:true},
    			{name: 'data_seq_id'   , index: 'data_seq_id', label: "主键"             , width: 180 ,hidden:true}
    		];
	        controlsQuery.mainGrd.grdId.jqGrid({
	              url:"",
			      datatype:"local",
			      mtype:"POST",
			     autowidth:true,//宽度根据父元素自适应
			      height:400,
			      shrinkToFit:true,
			      scroll:false,
			      resizable : true,
			      loadonce:true,
			      fixed: true,
			      jsonReader : {
			            // repeatitems: false
			          },
			      viewrecords : true, //显示总记录数
			      rownumbers  :true ,//显示行号
			      rowNum:50,         //每页多少行，用于分页
			      rownumWidth : 40,  //行号列宽度
			      emptyrecords :true ,
		          colModel: grdInfoCM,
		          onSelectRow:function(id){
			         toolFunc.diabledInput();
			         $("#customerTypSel").attr({"disabled":true});
	    			 $("#tab2").attr("href","#tabPane_dept" );
	    			 $("#tab4").attr("href","#settings" );
			         var rowData = $(this).jqGrid("getRowData",id);
			           toolFunc.QueryCustInfoProc();
		          }
	        });
    }
    var inilocGridInfo = function(){ 
   			var grdInfoCM = [
   				{name: 'modifyItem'   , index: 'modifyItem' , label: MODIFY_BTN_TAG  , width: 50 },
       			{name: 'deleteItem'   , index: 'deleteItem' , label: DELETE_BTN_TAG  , width: 50 },
	            {name: 'cus_id_fk'    , index: 'cus_id_fk'  , label: CUS_ID_TAG      , width: 100},
    			{name: 'cus_seq_id'   , index: 'cus_seq_id' , label: SEQ_NO_TAG      , width: 80 },
    			{name: 'loc_type'     , index: 'loc_type'   , label: ADRESS_TYPE_TAG , width: 50 },
    			{name: 'loc_info'     , index: 'loc_info'   , label: LOC_INFO_TAG    , width: 380 }
    		];
	        controlsQuery.locGrd.grdId.jqGrid({
	              url:"",
			      datatype:"local",
			      mtype:"POST",
			     autowidth:true,//宽度根据父元素自适应
			      height:300,
			      shrinkToFit:true,
			      scroll:false,
			      resizable : true,
			      loadonce:true,
			      fixed: true,
			      jsonReader : {
			            // repeatitems: false
			          },
			      viewrecords : true, //显示总记录数
			      rownumbers  :true ,//显示行号
			      rowNum:50,         //每页多少行，用于分页
			      rownumWidth : 40,  //行号列宽度
			      emptyrecords :true ,
		          colModel: grdInfoCM
	        });
    }
    controlsQuery.locGrd.grdId.jqGrid('navGrid','#locListPg',{ del:false,add:false,edit:false},{},{},{},{multipleSearch:true});
                         /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.query_func();
        });
        btnQuery.f4.click(function(){
            btnFunc.del_func();
        });
        btnQuery.f5.click(function(){
            btnFunc.update_func();
        });
        btnQuery.f6.click(function(){
            btnFunc.add_func();
        });
        btnQuery.f8.click(function(){
            btnFunc.register_func();
        });
        btnQuery.addBtn.click(function(){
        	toolFunc.addDivfunc();
        });
        btnQuery.addloc.click(function(){
        	btnFunc.addlocfunc();
        });
    };
    controlsQuery.loc_type.change(function(){
    	if( controlsQuery.loc_type.find("option:selected").text() == "R" ){
    		controlsQuery.locType_dsc.text("收货地址");
    	}else if( controlsQuery.loc_type.find("option:selected").text() == "S" ){
    		controlsQuery.locType_dsc.text("送货地址");
    	}
    })
    var initializationFunc = function(){
        iniGridInfo();
        toolFunc.initCustomerTypSel();
        inilocGridInfo();
        iniButtonAction();
        toolFunc.initFnc();
    };
    initializationFunc();
    var buttonCounts1 = [true,false,false,false,false,false,false,false,false,false];
});